﻿#include "cash_produce_dialog.h"
#include "ui_cash_produce_dialog.h"
#include <QSqlQuery>
#include <qdebug.h>
#include <QDate>
#include "produce_dialog.h"
#include "login_dialog.h"
#include <QMessageBox>
#include "addvip_dialog.h"
//收银界面
cash_produce_dialog::cash_produce_dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::cash_produce_dialog)
{
    ui->setupUi(this);
    ui->vipIdEdit->hide();
    //页面初始化设置，完善tableWidget显示的瑕疵
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    //条形码输入框商品ID范围限制
    QIntValidator *validator = new QIntValidator(1600, 1700, this);
    ui->editPID->setValidator(validator);
    //实收金额限制为数字
    QIntValidator *validator1 = new QIntValidator(this);
    ui->editRealget->setValidator(validator1);
    ui->settleBtn->setEnabled(false);
    ui->tableWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); //取消水平滚动条
    //connect(login,SIGNAL(sendName(QString)),this,SLOT(receiveData(QString)));
}

cash_produce_dialog::~cash_produce_dialog()
{
    delete ui;
}

void cash_produce_dialog::receiveData(QString data)
{
    ui->label->setText(data);
}

//添加商品显示数据  显示总价
void cash_produce_dialog::on_qrCodeBtn_2_clicked()
{
    QString PID = ui->editPID->text();
    QString sql = "select p_name,p_sell_price from produce where p_id='" +PID+ "'";
    QSqlQuery query;
    //query.exec()和query.next()都是QsqlQuery封装的执行函数
    query.exec(sql);
    if(query.next()){
        QString pname = query.value(0).toString();
        QString price = query.value(1).toString();
        int row = ui->tableWidget->rowCount();  //统计当前行
        for(int i = 0; i < row; i++){
            //在当前的tableWidget中插入数据，因为是for循环  一条一条的插入
            QString pName = ui->tableWidget->item(i, 0)->text();
            if(pName == pname)
            {
                //NUM为tableWidget中商品数量， 因为设置了两种添加商品的方式（1条形码查询插入2新窗口选择插入（信号槽实现））
                //所以添加数量设置为全局变量
                cash_produce_dialog::NUM += 1;
                ui->tableWidget->removeRow(i);
            }
        }

        //以下是点击添加按钮之后初始化界面数据
        QTableWidgetItem *pPriceItem=new QTableWidgetItem(price);
        QTableWidgetItem *pNameItem=new QTableWidgetItem(pname);
        QTableWidgetItem *pNumItem=new QTableWidgetItem(QString::number(NUM));

        int i = ui->tableWidget->rowCount();
        ui->tableWidget->insertRow(i);
        ui->tableWidget->setItem(i,0,pNameItem);
        ui->tableWidget->setItem(i,1,pPriceItem);
        ui->tableWidget->setItem(i,2,pNumItem);

        int allrow = ui->tableWidget->rowCount();
        int allconsume = 0;

        //在已有行数的下一行插入数据
        for(int i = 0; i <= (allrow-1); i++) {
            int price = ui->tableWidget->item(i,1)->text().toInt();
            int num = ui->tableWidget->item(i,2)->text().toInt();
            allconsume += (price*num);
        }

        //使用更新标签的形式让界面总价和折扣价金额的显示
        ui->AllConLabel->setText(QString(to_string(allconsume).c_str())); // 使用to_String 转换
        ui->disConLabel->setText(QString(to_string(allconsume).c_str()));
    }

}

//RadioButton点击显示会员等操作框
void cash_produce_dialog::on_vipRBtn_clicked(bool checked)
{
    if(checked){
        ui->vipIdEdit->setStyleSheet("background-color: rgb(255,255,255);");
        ui->vipIdEdit->setReadOnly(false);

        ui->vipIdEdit->show();
        vipSelected = checked;

    }else{
        ui->vipIdEdit->setReadOnly(true);
        ui->vipIdEdit->hide();
        ui->vipIdEdit->setStyleSheet("background-color:rgb(211, 215, 207);");
    }
}

//结帐按钮
void cash_produce_dialog::on_settleBtn_clicked()
{

    QSqlQuery query;

    int allrow = ui->tableWidget->rowCount();
    for(int i = 0; i <= (allrow-1); i++) {
        //更改数据库产品数量
        QString pname = ui->tableWidget->item(i, 0)->text();
        int num = ui->tableWidget->item(i, 2)->text().toInt();
        QString selSql = "select p_num from produce where p_name='" +pname+ "'";
        int subnum = 0;

        query.exec(selSql);
        while(query.next()){
            int oldnum = query.value(0).toInt();
            subnum = oldnum - num;
        }
        QString upSql = "update produce set p_num=" + QString::number(subnum)
                + " where p_name='" +pname+ "'";
        query.exec(upSql);

        //在订单表中插入这次购物的信息
        QDateTime time;
        QString delTime=QString(time.currentDateTime().toString("yyyy") + "年" +\
                                time.currentDateTime().toString("MM")+"月" + \
                                time.currentDateTime().toString("dd")+"日" + \
                                time.currentDateTime().toString("h")+"时" + \
                                time.currentDateTime().toString("m")+"分" + \
                                time.currentDateTime().toString("s") +"秒");
        QString afterDis = ui->disConLabel->text();
        QString userName = ui->label->text();

        QString insSql = "insert into dealing(d_price, username, p_date) values('" +afterDis+ "','" +userName+ "','" +delTime+ "')";
        query.exec(insSql);

    }
    //清除表格数据
    while(ui->tableWidget->rowCount())
    {
      ui->tableWidget->removeRow(0);
    }
    //结帐清空数据
    ui->vipRBtn->setChecked(false);
    ui->AllConLabel->setText("0");
    ui->disConLabel->setText("0");
    ui->changeLabel->setText("0");
    ui->editRealget->clear();
    ui->vipIdEdit->clear();
    ui->editPID->clear();
    NUM = 1;

   QMessageBox::about(NULL, "提示", "付款成功！");


}

//信号槽实现另一个界面添加商品的功能
void cash_produce_dialog::on_addProBtn_clicked()
{
    produce_dialog *addProduce = new produce_dialog();
    connect(addProduce,SIGNAL(addPro(QString, QString, QString)),this,SLOT(addPro(QString, QString, QString)));
    addProduce->exec();
}

//槽 接受顾客选定的商品信息进行处理 更新表格显示数据
void cash_produce_dialog::addPro(QString proName, QString price, QString num)
{
    QTableWidgetItem *pNameItem = new QTableWidgetItem (proName);
    QTableWidgetItem *pPriceItem = new QTableWidgetItem (price);
    QTableWidgetItem *pNumItem = new QTableWidgetItem (num);

    int row = ui->tableWidget->rowCount();
    //遍历表格中商品名称进行判断是新添加商品 还是更新已有商品的数量
    for(int i = 0; i < row; i++){
        QString pName = ui->tableWidget->item(i, 0)->text();
        if(proName == pName){
            int oldNum = ui->tableWidget->item(i, 2)->text().toInt();
            int toNum = num.toInt();
            int allNum = toNum + oldNum;

            QTableWidgetItem *pNumItem = new QTableWidgetItem (QString::number(allNum));
            //qDebug()<<allNum;
            ui->tableWidget->setItem(i, 2, pNumItem);
            break;
        }
        else
        {
            ui->tableWidget->insertRow(row);
            ui->tableWidget->setItem(row, 0, pNameItem);
            ui->tableWidget->setItem(row, 1, pPriceItem);
            ui->tableWidget->setItem(row, 2, pNumItem);
        }
    }


    if(row == 0){
        ui->tableWidget->insertRow(row);

        ui->tableWidget->setItem(row, 0, pNameItem);
        ui->tableWidget->setItem(row, 1, pPriceItem);
        ui->tableWidget->setItem(row, 2, pNumItem);
    }
    //未封装更新价格标签的代码  跟上边点击添加商品按钮更新标签显示的代码相同
    int allrow = ui->tableWidget->rowCount();
    int allconsume = 0;
    for(int i = 0;i <= (allrow-1); i++) {
        int price = ui->tableWidget->item(i,1)->text().toInt();
        int num = ui->tableWidget->item(i,2)->text().toInt();
        allconsume += (price * num);
    }

    ui->AllConLabel->setText(QString(to_string(allconsume).c_str())); // 使用to_String 转换
    ui->disConLabel->setText(QString(to_string(allconsume).c_str()));
}

//删除表格中数据的按钮
void cash_produce_dialog::on_delProBtn_clicked()
{
    int row = ui->tableWidget->currentRow();
    if(row >= 0) {
        QTableWidgetItem *pNameItem = ui->tableWidget->item(row, 0);
        QString name = pNameItem->text();
         ui->tableWidget->removeRow(row);
    }
}

//显示收银员的姓名
void cash_produce_dialog::init() {
    this->ui->label->setText(this->USER);
}

//检查会员并打折
void cash_produce_dialog::on_vipIdEdit_returnPressed()
{
    //找零
    int afterDis = 0;
    int beforeDis = ui->AllConLabel->text().toInt();    //allconsume
    double discount = 1.0;
    QSqlQuery query;
    if(vipSelected){
        QString vipid = ui->vipIdEdit->text();
        QString sql = "select v_level from vip where v_id=" +vipid+ ";";  //记录
        query.exec(sql);
        if(query.next()){
             QString vipLevel = query.value(0).toString();

             if(vipLevel == "白银会员"){  discount = 0.9;}
             if(vipLevel == "黄金会员"){  discount = 0.8;}
             if(vipLevel == "钻石会员"){  discount = 0.7;}
             if(vipLevel == "黑曜会员"){  discount = 0.6;}
             QMessageBox::about(NULL, "提示", tr("折扣为：%1折").arg(discount * 10));
         }
        else
        {
            QMessageBox::about(NULL, "警告", "无此会员,无折扣");
        }
    }
    //折后价并更新
    afterDis = beforeDis * discount;
    ui->disConLabel->setText(QString(to_string(afterDis).c_str()));
}

//实收价格显示
void cash_produce_dialog::on_editRealget_returnPressed()
{
    int realGetPrice = ui->editRealget->text().toInt();
    int change = 0;
    int afterDis = ui->disConLabel->text().toInt();
    change = realGetPrice - afterDis;
    if(change < 0){
        QMessageBox::about(NULL, "警告", "实收金额不足，请加钱！");
        ui->editRealget->setFocus();
    }else{
        ui->changeLabel->setText(QString(to_string(change).c_str()));
        ui->settleBtn->setEnabled(true);
    }
}

//点击添加会员会向添加会员界面发送标识FLAG为1
void cash_produce_dialog::on_addVIPBtn_clicked()
{
    addvip_dialog *addvip = new addvip_dialog();
    addvip->FLAG = "1";
    addvip->exec();
}

void cash_produce_dialog::on_qrCodeBtn_clicked()
{
    // QMessageBox::about(NULL, "提示", "无外连设备，请外接设备之后使用");
}
